package tt.dz.service.imp.sys;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import redis.clients.jedis.Jedis;
import tt.dz.dao.base.OmsCommonDao;
import tt.dz.dao.ext.base.OmsDeviceTypeDao;
import tt.dz.dao.ext.charger.OmsChargerBespeakBillRecordDao;
import tt.dz.dao.ext.charger.OmsChargerChargeBillRecordDao;
import tt.dz.dao.ext.charger.OmsChargerDao;
import tt.dz.dao.ext.charger.OmsChargerErrorRecordDao;
import tt.dz.dao.ext.charger.OmsChargerRateDao;
import tt.dz.dao.ext.charger.OmsChargerStateAlternateDao;
import tt.dz.dao.ext.charger.OmsChargerStateDirectDao;
import tt.dz.dao.ext.common.OmsSplitratioSchemeDao;
import tt.dz.dao.ext.common.OmsWhiteListDao;
import tt.dz.dao.ext.dic.OmsDicForwardSrvInfoDao;
import tt.dz.dao.ext.station.OmsStationDao;
import tt.dz.entity.base.JsonCommon;
import tt.dz.entity.base.JsonForList;
import tt.dz.entity.base.JsonPageForList;
import tt.dz.entity.base.OmsCommonParam;
import tt.dz.entity.base.OmsDeviceType;
import tt.dz.entity.base.OmsPubWhitelist;
import tt.dz.entity.base.OmsServiceSplitratio;
import tt.dz.entity.base.OmsSplitratioScheme;
import tt.dz.entity.bigscreen.ScreenCharger;
import tt.dz.entity.charger.OmsCharger;
import tt.dz.entity.charger.OmsChargerBespeakBillRecord;
import tt.dz.entity.charger.OmsChargerChargeBillRecord;
import tt.dz.entity.charger.OmsChargerNo;
import tt.dz.entity.charger.OmsChargerRate;
import tt.dz.entity.charger.OmsChargerStateAlternate;
import tt.dz.entity.charger.OmsChargerStateDirect;
import tt.dz.entity.dic.OmsDicForwardSrvInfo;
import tt.dz.entity.station.OmsStation;
import tt.dz.entity.system.OmsOperList;
import tt.dz.mvc.controller.base.BaseAction;
import tt.dz.service.middleware.MessageService;
import tt.dz.service.sys.ChargerService;
import tt.dz.util.OmsConstant;
import tt.dz.util.OmsConstant.MsgCodeEnum;
import tt.dz.util.RedisClient;
import tt.dz.util.StringUtil;
import tt.dz.vo.oms.ChargerCountAndInfoVO;
import tt.dz.vo.oms.ChargerExportVO;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ChargerServiceImpl implements ChargerService {
	@Resource
	OmsChargerDao omsChargerDao;
	@Resource
	OmsStationDao omsStationDao;
	@Resource
	OmsChargerStateDirectDao stateDirectDao;
	@Resource
	OmsChargerStateAlternateDao stateAlternateDao;
	@Resource
	OmsChargerBespeakBillRecordDao bespeakBillRecordDao;
	@Resource
	OmsChargerChargeBillRecordDao chargeBillRecordDao;
	@Resource
	OmsChargerErrorRecordDao errorRecordDao;
	@Resource
	OmsChargerStateAlternateDao omsChargerStateAlternateDao;
	@Resource
	OmsChargerStateDirectDao omsChargerStateDirectDao;
	@Resource
	OmsChargerRateDao omsChargerRateDao;
	@Resource
	OmsDicForwardSrvInfoDao omsDicForwardSrvInfoDao;
	@Resource
	OmsSplitratioSchemeDao omsSplitratioSchemeDao;
	@Resource
	OmsDeviceTypeDao omsDeviceTypeDao;
	@Resource
	OmsWhiteListDao omsWhiteListDao;
	@Autowired
	private HttpServletRequest request;

	@Autowired
	@Qualifier("base")
	private OmsCommonDao<OmsServiceSplitratio> serviceSplitratioDaoImpl;
	@Resource(name = "ev3cMessageServiceImpl")
	MessageService ev3cMessageService;
	private Log log = LogFactory.getLog(ChargerServiceImpl.class);

	public String getChargerList(OmsCharger charger) {
		List<OmsCharger> list = omsChargerDao.findExample(charger, null, null, null, null);
		// list.get(0).setUser_pay_card("111111111");
		JsonForList<OmsCharger> jList = new JsonForList<OmsCharger>();
		jList.setCode("200");
		jList.setMsg("ok");
		jList.setList(list);
		String jsonString = JSON.toJSONString(jList);
		return jsonString;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public JsonForList updateCharger(OmsCharger charger) {
		int result = omsChargerDao.updateObject(charger);
		// JsonCommon jsonC = new JsonCommon();
		JsonForList json = new JsonForList();
		if (result > 0) {
			json.setCode("200");
			json.setMsg("updateCharger ok");
			// String jsonString = JSON.toJSONString(jsonC);
			// return jsonString;
		} else {
			json.setCode("400");
			json.setMsg("updateCharger fail");
			// String jsonString = JSON.toJSONString(jsonC);
			// return jsonString;
		}
		return json;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public JsonForList deleteCharger(List<String> list, String oper_id, String chargerType) throws Exception {
		// 获取这些删除桩的所属站点ID、桩类型、数量：select
		// oms_charger.station_id,oms_charger.charger_type,count(1) from
		// oms_charger group by oms_charger.station_id,oms_charger.charger_type
		// 原有删除桩，并不查询桩的状态，可能导致正在预约或者充电的桩呗删除
		/*
		 * JsonForList jsonForList = omsChargerDao.deleteCharger(list, oper_id);
		 * if (jsonForList.getCode().equals("200")) { StringBuffer sql = new
		 * StringBuffer(); sql.append(
		 * "select station_id,charger_type,count(1) cn from oms_charger where charger_id in ("
		 * ); for(String str :list){ sql.append("'"+str+"',"); }
		 * sql.deleteCharAt(sql.length()-1); sql.append(
		 * ") group by station_id,charger_type");
		 * 
		 * List<Map<String, Object>> listTmp =
		 * omsChargerDao.findDataBySql(sql.toString()); for(Map<String, Object>
		 * mapTmp : listTmp) { String station_id =
		 * (String)mapTmp.get("station_id"); if
		 * (StringUtil.isNotBlank(station_id)) { Integer directCount = 0;
		 * Integer alternateCount = 0; if ((Integer)mapTmp.get("charger_type")
		 * == 1 ) { directCount = Integer.valueOf(mapTmp.get("cn").toString());
		 * }else if ((Integer)mapTmp.get("charger_type") == 2 ) { alternateCount
		 * = Integer.valueOf(mapTmp.get("cn").toString()); }
		 * omsChargerDao.deleteChargerForStation(station_id,directCount,
		 * alternateCount); } } }else { return jsonForList; }
		 */

		int updateNum = omsChargerDao.deleteChargerByStatus(list, oper_id, chargerType);
		if (list.size() != updateNum) {
			// 逻辑删除桩时，要添加条价（桩的状态）；这样可能会发生一些选择的桩不会被逻辑删除，则导致不知道具体删除了哪些桩，因此就不能更新站点的桩数量信息，
			// 抛出异常，然后触发事务回滚
			throw new Exception("你选择的桩中，有些已经被预约或者正在充电，导致删除失败！");
		} else {
			// 桩删除后，同时删除装的枪口信息
			if (!omsChargerDao.deleteChargerPort(list, chargerType)) {
				// 抛出异常，触发事务回滚
				throw new Exception("删除枪口信息失败！");
			}
			StringBuffer sql = new StringBuffer();
			sql.append("select station_id,charger_type,count(1) cn from oms_charger where charger_id in (");
			for (String str : list) {
				sql.append("'" + str + "',");
			}
			sql.deleteCharAt(sql.length() - 1);
			sql.append(") group by station_id,charger_type");

			List<Map<String, Object>> listTmp = omsChargerDao.findDataBySql(sql.toString());
			for (Map<String, Object> mapTmp : listTmp) {
				String station_id = (String) mapTmp.get("station_id");
				if (StringUtil.isNotBlank(station_id)) {
					Integer directCount = 0;
					Integer alternateCount = 0;
					if ((Integer) mapTmp.get("charger_type") == 1) {
						directCount = Integer.valueOf(mapTmp.get("cn").toString());
					} else if ((Integer) mapTmp.get("charger_type") == 2) {
						alternateCount = Integer.valueOf(mapTmp.get("cn").toString());
					}
					omsChargerDao.deleteChargerForStation(station_id, directCount, alternateCount);
				}
			}
		}

		JsonForList json = new JsonForList();
		json.setCode("200");
		return json;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public JsonForList getChargerListByStation(OmsCharger charger) {
		List<OmsCharger> list = omsChargerDao.findExample(charger, null, null, null, null);
		for (OmsCharger chargerTemp : list) {
			switch (chargerTemp.getCharger_type()) {// 1--直流 2--交流 3--混合
			case 1:
				OmsChargerStateDirect direct_query = new OmsChargerStateDirect();
				direct_query.setCharger_id(chargerTemp.getCharger_id());
				List<OmsChargerStateDirect> lsDirect = stateDirectDao.findExample(direct_query, null, null, null, null);
				if (lsDirect != null) {
					List<Integer> lsStatus = new ArrayList<Integer>();
					for (OmsChargerStateDirect direct : lsDirect) {
						lsStatus.add(direct.getCharge_status());
					}
					chargerTemp.setPortStatusList(lsStatus);
				}
				break;
			case 2:
				OmsChargerStateAlternate alt_query = new OmsChargerStateAlternate();
				alt_query.setCharger_id(chargerTemp.getCharger_id());
				OmsChargerStateAlternate alt = stateAlternateDao.findOneExample(alt_query, null, null);
				if (alt != null) {
					chargerTemp.setCharge_status(alt.getCharge_status());
				}
				break;
			default:
				break;
			}
		}
		JsonForList<OmsCharger> jList = new JsonForList<OmsCharger>();
		jList.setCode("200");
		jList.setMsg("ok");
		jList.setList(list);
		// String jsonString = JSON.toJSONString(jList);
		// return jsonString;
		return jList;
	}

	// // 查询单个桩的详情
	// @SuppressWarnings({ "rawtypes", "unchecked" })
	// @Override
	// public JsonForList getChargerDetail(String charger_id) {
	// OmsCharger charger_query = new OmsCharger();
	// JsonForList json = new JsonForList();
	// charger_query.setCharger_id(charger_id);
	// // 一个桩多个枪
	// OmsCharger charger_1 = omsChargerDao.findOneExample(charger_query, null,
	// null);
	// if (charger_1 == null) {
	// json.setCode("400");
	// json.setMsg("charger_id:" + charger_id + " query charger null ");
	// return json;
	// }
	// List<OmsCharger> chargerList = new ArrayList<OmsCharger>();
	// for (int i = 0; i < charger_1.getPort_quantity(); i++) {
	// try {
	// OmsCharger charger_temp = (OmsCharger) charger_1.clone();
	// charger_temp.setPort_no(i);
	// chargerList.add(charger_temp);
	// } catch (CloneNotSupportedException e) {
	// json.setCode("400");
	// json.setMsg("charger_id:" + charger_id + " query charger null ");
	// e.printStackTrace();
	// return json;
	// }
	// }
	// // Student student2 = (Student) student1.clone();
	// for (OmsCharger charger : chargerList) {
	// switch (charger.getCharger_type()) {// 1--直流 2--交流 3--混合
	// case 1:
	// OmsChargerStateDirect direct_query = new OmsChargerStateDirect();
	// direct_query.setCharger_id(charger_id);
	// OmsChargerStateDirect direct =
	// stateDirectDao.findOneExample(direct_query, null, null);
	// if (direct != null) {
	// if (direct.getOnline_status() == 0) {// 1代表在线 0代表离线
	// charger.setCharge_status(10);
	// charger.setCharge_status_start_time(direct.getLast_connect_time());
	// charger.setOffline_time(StringUtil.timeDifference(direct.getLast_connect_time()));
	// } else {
	// charger.setCharge_status(direct.getCharge_status());
	// switch (direct.getCharge_status()) {// 0: 空闲;1: 预约;2 充电;
	// // 3 故障
	// case 0:
	// break;
	// case 1:
	// OmsChargerBespeakBillRecord bespeakBillRecord_query = new
	// OmsChargerBespeakBillRecord();
	// bespeakBillRecord_query.setCharger_id(charger_id);
	// bespeakBillRecord_query.setPort_no(charger.getPort_no());
	// OmsChargerBespeakBillRecord bespeakBillRecord = bespeakBillRecordDao
	// .findOneExample(bespeakBillRecord_query, "create_time", "desc");
	// charger.setCharge_status_start_time(bespeakBillRecord.getStart_time());
	// charger.setUser_pay_card(bespeakBillRecord.getUser_pay_card());
	// break;
	// case 2:
	// OmsChargerChargeBillRecord chargeBillRecord_query = new
	// OmsChargerChargeBillRecord();
	// chargeBillRecord_query.setCharger_id(charger_id);
	// chargeBillRecord_query.setPort_no(charger.getPort_no());
	// OmsChargerChargeBillRecord chargeBillRecord = chargeBillRecordDao
	// .findOneExample(chargeBillRecord_query, "create_time", "desc");
	// charger.setCharge_status_start_time(chargeBillRecord.getStart_time());
	// charger.setUser_pay_card(chargeBillRecord.getUser_pay_card());
	// break;
	// case 3:
	// OmsChargerErrorRecord errorRecord_query = new OmsChargerErrorRecord();
	// errorRecord_query.setCharger_id(charger_id);
	// OmsChargerErrorRecord errorRecord =
	// errorRecordDao.findOneExample(errorRecord_query,
	// "create_time", "desc");
	// if (errorRecord != null) {
	// charger.setCharge_status_start_time(errorRecord.getCreate_time());
	// charger.setError_msg(errorRecord.getError_msg());
	// }
	// break;
	// default:
	// break;
	// }
	// }
	// }
	// break;
	// case 2:
	// OmsChargerStateAlternate alt_query = new OmsChargerStateAlternate();
	// alt_query.setCharger_id(charger_id);
	// OmsChargerStateAlternate alt =
	// stateAlternateDao.findOneExample(alt_query, null, null);
	// if (alt != null) {
	// if (alt.getOnline_status() == 0) {// 1代表在线 0代表离线
	// charger.setCharge_status(10);
	// charger.setCharge_status_start_time(alt.getLast_connect_time());
	// charger.setOffline_time(StringUtil.timeDifference(alt.getLast_connect_time()));
	// } else {
	// charger.setCharge_status(alt.getCharge_status());
	// switch (alt.getCharge_status()) {// 0: 空闲;1: 预约;2 充电; 3
	// // 故障
	// case 0:
	// break;
	// case 1:
	// OmsChargerBespeakBillRecord bespeakBillRecord_query = new
	// OmsChargerBespeakBillRecord();
	// bespeakBillRecord_query.setCharger_id(charger_id);
	// bespeakBillRecord_query.setPort_no(charger.getPort_no());
	// OmsChargerBespeakBillRecord bespeakBillRecord = bespeakBillRecordDao
	// .findOneExample(bespeakBillRecord_query, "create_time", "desc");
	// charger.setCharge_status_start_time(bespeakBillRecord.getStart_time());
	// charger.setUser_pay_card(bespeakBillRecord.getUser_pay_card());
	// break;
	// case 2:
	// OmsChargerChargeBillRecord chargeBillRecord_query = new
	// OmsChargerChargeBillRecord();
	// chargeBillRecord_query.setCharger_id(charger_id);
	// chargeBillRecord_query.setPort_no(charger.getPort_no());
	// OmsChargerChargeBillRecord chargeBillRecord = chargeBillRecordDao
	// .findOneExample(chargeBillRecord_query, "create_time", "desc");
	// charger.setCharge_status_start_time(chargeBillRecord.getStart_time());
	// charger.setUser_pay_card(chargeBillRecord.getUser_pay_card());
	// break;
	// case 3:
	// OmsChargerErrorRecord errorRecord_query = new OmsChargerErrorRecord();
	// errorRecord_query.setCharger_id(charger_id);
	// OmsChargerErrorRecord errorRecord =
	// errorRecordDao.findOneExample(errorRecord_query,
	// "create_time", "desc");
	// if (errorRecord != null) {
	// charger.setCharge_status_start_time(errorRecord.getCreate_time());
	// charger.setError_msg(errorRecord.getError_msg());
	// }
	// break;
	// default:
	// break;
	// }
	// }
	// }
	// break;
	// default:
	// break;
	// }
	// }
	// //查询预约费率
	// if(){
	//
	// }
	// OmsChargerRate bespeakRate = omsChargerRateDao.findExample(new
	// OmsChargerRate(), null, null, null, null);
	// //查询充电费率
	// //查询服务费费率
	// //查询硬件服务器
	// //查询分成方案
	// //查询设备信息
	// //查询白名单
	// JsonForList<OmsCharger> jsonList = new JsonForList();
	// jsonList.setList(chargerList);
	// jsonList.setCode("200");
	// jsonList.setMsg("query ok");
	// return jsonList;
	// }

	// 查询单个桩的详情,不包括桩的详情
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public JsonCommon getChargerDetail(String charger_id) {
		JsonCommon json = new JsonCommon();
		// 一个桩多个枪
		OmsCharger charger = omsChargerDao.findOneExample(new OmsCharger(charger_id), null, null);
		if (charger == null) {
			json.setCode("400");
			json.setMsg("charger_id:" + charger_id + " query charger null ");
			return json;
		}

		// 查询预约费率
		if (charger.getRate_schema_bespeak_fee() != null) {
			List<OmsChargerRate> bespeakRateList = omsChargerRateDao
					.findExample(new OmsChargerRate(charger.getRate_schema_bespeak_fee()), null, null, null, null);
			charger.setBespeakRateList(bespeakRateList);
		}
		// 查询服务费费率
		if (charger.getRate_schema_service_fee() != null) {
			List<OmsChargerRate> chargeServiceRateList = omsChargerRateDao
					.findExample(new OmsChargerRate(charger.getRate_schema_service_fee()), null, null, null, null);
			charger.setChargeServiceRateList(chargeServiceRateList);
		}
		// 查询充电费率
		if (charger.getRate_schema_charge_fee() != null) {
			List<OmsChargerRate> chargeRateList = omsChargerRateDao
					.findExample(new OmsChargerRate(charger.getRate_schema_charge_fee()), null, null, null, null);
			charger.setChargeRateList(chargeRateList);
		}
		// 查询硬件服务器
		if (charger.getForward_srv_id() != null) {
			OmsDicForwardSrvInfo omsDicForwardSrvInfo = omsDicForwardSrvInfoDao
					.findOneExample(new OmsDicForwardSrvInfo(charger.getForward_srv_id()), null, null);
			charger.setOmsDicForwardSrvInfo(omsDicForwardSrvInfo);
		}
		// 查询分成方案
		List<OmsSplitratioScheme> list_OmsSplitratioScheme = new ArrayList<OmsSplitratioScheme>();
		List<OmsServiceSplitratio> omsServiceSplitratioList = serviceSplitratioDaoImpl
				.findExample(new OmsServiceSplitratio(charger_id), null, null, null, null);
		for (OmsServiceSplitratio splitratio_temp : omsServiceSplitratioList) {// 取出服务编号
																				// 和方案号
			// splitratio_temp
			OmsSplitratioScheme splitratioScheme_query = new OmsSplitratioScheme();
			splitratioScheme_query.setService_no(splitratio_temp.getService_no());
			splitratioScheme_query.setScheme_no(splitratio_temp.getScheme_no());
			List<OmsSplitratioScheme> list_temp = null;
			if (StringUtil.isNotBlank(splitratio_temp.getService_no())) {
				// List<OmsSplitratioScheme> list_temp =
				// omsSplitratioSchemeDao.findExample(splitratioScheme_query,
				// null, null, "service_no,scheme_no", 1);//ASC
				list_temp = omsSplitratioSchemeDao.findListByPageAndGroupAndOrderAndCondition(new OmsSplitratioScheme(),
						" where scheme_no = " + splitratio_temp.getScheme_no(), null, null, null, null, "scheme_no");
				if (list_temp.size() > 0) {
					list_OmsSplitratioScheme.addAll(list_temp);
				}
			}

		}
		charger.setOmsSplitratioSchemeList(list_OmsSplitratioScheme);
		// 查询设备信息
		if (charger.getDevice_id() != null) {
			OmsDeviceType omsDeviceType = (OmsDeviceType) omsDeviceTypeDao
					.findOneExample(new OmsDeviceType(charger.getDevice_id()), null, null);
			charger.setOmsDeviceType(omsDeviceType);
		}
		// 运营商名字
		if (charger.getOper_merchant_id() != null) {
			String sql = "select oper_name from oms_operation_sp_list  where oper_merchant_id = '"
					+ charger.getOper_merchant_id() + "'";
			List<Map<String, Object>> list_tmp = omsDeviceTypeDao.findDataBySql(sql, null);
			if (CollectionUtils.isNotEmpty(list_tmp)) {
				charger.setOperName((String) list_tmp.get(0).get("oper_name"));
			}
			// charger.setOmsDeviceType(omsDeviceType);
		}
		// 所属实体名称
		if (charger.getEntity_id() != null) {
			String sql = "select name from oms_normal_sp_list  where merchant_id = '" + charger.getEntity_id() + "'";
			List<Map<String, Object>> list_tmp = omsDeviceTypeDao.findDataBySql(sql, null);
			if (CollectionUtils.isNotEmpty(list_tmp)) {
				charger.setEntityName((String) list_tmp.get(0).get("name"));
			}
			// charger.setOmsDeviceType(omsDeviceType);
		}

		// 所属实体名称
		if (charger.getFactory_id() != null) {
			String sql = "select factory_name,brand from oms_factory_list  where factory_id = '"
					+ charger.getFactory_id() + "'";
			List<Map<String, Object>> list_tmp = omsDeviceTypeDao.findDataBySql(sql, null);
			if (CollectionUtils.isNotEmpty(list_tmp)) {
				charger.setFactory_name((String) list_tmp.get(0).get("factory_name"));
				charger.setBrand((String) list_tmp.get(0).get("brand"));
			}
		}
		// 查询白名单
		List<OmsPubWhitelist> whitelist = omsWhiteListDao.findExample(new OmsPubWhitelist(charger_id), null, null, null,
				null);
		charger.setWhitelist(whitelist);
		return new JsonCommon(charger, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
				OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@Override
	public List<OmsCharger> findAll() {
		return omsChargerDao.findAll(new OmsCharger());
	}

	@Override
	public List<OmsCharger> getChargerByIds(String chargerIds) {
		String[] list = chargerIds.split(",");
		StringBuilder sb = new StringBuilder("where 1=1 ");
		if (list != null && list.length > 0) {
			sb.append("and charger_id in (");
			for (String str : list) {
				sb.append("'" + str + "',");
			}
			sb.deleteCharAt(sb.length() - 1);
			sb.append(")");
		}

		OmsCharger charger = new OmsCharger();
		return omsChargerDao.findListByCondition(charger, sb.toString());
	}

	@Override
	public List<ChargerExportVO> getExportData(Integer chargerType, String[] list_chargerId) {
		StringBuffer sql = new StringBuffer();
		sql.append(
				" SELECT c.charger_id, t.port_stats, c.station_id, s.station_name, di.district_name, c.charger_type, c.qr_code, c.port_quantity, c.oper_merchant_id, m.oper_name, c.entity_id,  ");
		sql.append(
				" 	n.NAME partner_name, c.installation_time, c.serial_no, c.factory_id, f.factory_name, c.dev_sn, c.software_version, c.protocol_version, c.rate_schema_bespeak_fee,  ");
		sql.append(" 	c.rate_schema_charge_fee, c.rate_schema_service_fee, c.is_allow_generate_fee ");
		sql.append(" FROM oms_charger c ");
		sql.append(" INNER JOIN oms_factory_list f ON f.factory_id = c.factory_id ");
		sql.append(" INNER JOIN ( ");
		sql.append(" 	SELECT e.charger_id, GROUP_CONCAT(CONCAT (port_no, ':', o.description)) port_stats ");
		sql.append(" 	FROM ( ");
		sql.append(" 		SELECT a.charger_id, a.port_no, a.charge_status ");
		sql.append(" 		FROM oms_charger_state_alternate a ");
		sql.append(" 		WHERE a.valid_flag = 1		 ");
		sql.append(" 		UNION ALL		 ");
		sql.append(" 		SELECT d.charger_id, d.port_no, d.charge_status ");
		sql.append(" 		FROM oms_charger_state_direct d ");
		sql.append(" 		WHERE d.valid_flag = 1 ");
		sql.append(" 		) e ");
		sql.append(" 	INNER JOIN oms_code o ON e.charge_status = o.code AND o.code_type = 'ChgStat' ");
		sql.append(" 	GROUP BY charger_id ");
		sql.append(" 	) t ON c.charger_id = t.charger_id ");
		sql.append(" LEFT JOIN oms_station s ON c.station_id = s.station_id ");
		sql.append(" LEFT JOIN oms_dic_district_code di ON di.district_code = s.district_code ");
		sql.append(" LEFT JOIN oms_operation_sp_list m ON c.oper_merchant_id = m.oper_merchant_id ");
		sql.append(" LEFT JOIN oms_normal_sp_list n ON n.merchant_id = c.entity_id ");
		sql.append(" WHERE c.valid_flag = 1 ");

		if (chargerType != null)
			sql.append(" AND c.charger_type = '").append(chargerType).append("' ");

		if (list_chargerId != null && list_chargerId.length > 0) {
			sql.append(" AND c.charger_id IN (");
			int i = 0;
			for (String chargerId : list_chargerId) {
				if (i == 0)
					sql.append("'").append(chargerId).append("'");
				else
					sql.append(" , '").append(chargerId).append("'");
				i++;
			}
			sql.append(" ) ");
		}
		return omsChargerDao.exportChargers(sql.toString());
	}

	@SuppressWarnings("rawtypes")
	@Override
	public JsonForList getChargerListTest(OmsCharger charger) {
		List<OmsCharger> list = omsChargerDao.findExample(charger, null, null, null, null);
		// list.get(0).setUser_pay_card("111111111");
		JsonForList<OmsCharger> jList = new JsonForList<OmsCharger>();
		jList.setCode("200");
		jList.setMsg("ok");
		jList.setList(list);
		// String jsonString = JSON.toJSONString(jList);
		return jList;
	}

	// @Override
	// public OmsCharger getChargerById(String charger_id, int port_no) {
	// OmsCharger charger = new OmsCharger();
	// charger.setCharger_id(charger_id);
	// charger.setPort_no(port_no);
	// return omsChargerDao.findOneExample(charger, null, null);
	//
	// }

	@Override
	public List<OmsCharger> getList(OmsCharger charger) {
		return omsChargerDao.findExample(charger, null, null, null, null);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public JsonForList updateChargerList(List<OmsCharger> chargerList) {
		int result = 0;
		for (OmsCharger omsCharger : chargerList) {
			result = omsChargerDao.updateObject(omsCharger);
		}
		JsonForList json = new JsonForList();
		if (result > 0) {
			json.setCode("200");
			json.setMsg("updateCharger ok");
			// String jsonString = JSON.toJSONString(jsonC);
			// return jsonString;
		} else {
			json.setCode("400");
			json.setMsg("updateCharger fail");
			// String jsonString = JSON.toJSONString(jsonC);
			// return jsonString;
		}
		return json;
	}

	// 根据当前桩号前四位来查询出最大的qr_code号，来生成一个新的Qr_code号码
	@Override
	public synchronized String updateQrCode(String charger_id) {
		if (StringUtil.isBlank(charger_id) || charger_id.length() < 4
				|| !StringUtil.isNumeric(charger_id.substring(0, 4))) {
			return null;
		}
		String new_qr_code = "";
		OmsCharger omsChargerForQrCode = omsChargerDao.findOneExampleByCondition(new OmsCharger(),
				" where charger_id like '" + charger_id.substring(0, 4)
						+ "%' and  LENGTH(qr_code)= 12 order by qr_code desc");
		if (omsChargerForQrCode != null) {
			String qr_code = omsChargerForQrCode.getQr_code();
			new_qr_code = qr_code.substring(0, 4)
					+ StringUtil.complement(String.valueOf(Integer.valueOf(qr_code.substring(4)) + 1), 8);
		} else {
			new_qr_code = charger_id.substring(0, 4) + "00000001";// 12位
		}
		OmsCharger omsCharger_query = new OmsCharger();
		omsCharger_query.setCharger_id(charger_id);
		OmsCharger charger = omsChargerDao.findOneExample(omsCharger_query, null, null);
		if (charger != null) {
			charger.setQr_code(new_qr_code);
			updateCharger(charger);
		}
		return new_qr_code;
	}

	public String getQrCode1(String charger_id) {
		if (charger_id != null) {
			String qr_code = "510387654321";
			String new_qr_code = qr_code.substring(0, 4)
					+ StringUtil.complement(String.valueOf(Integer.valueOf(qr_code.substring(4)) + 1), 8);
			return new_qr_code;
		}
		return charger_id.substring(0, 4) + "00000001";// 12位
	}

	public static void main(String[] args) {
		// ChargerServiceImpl as = new ChargerServiceImpl();
		// System.out.println(as.getQrCode1("510312345678"));

		System.out.println(StringUtil.complement("12345678", 8));
		System.out.println(StringUtil.complement("1234567", 8));

	}

	@Override
	public List<Map<String, Object>> findDataBySql(String sql, Object params) {
		return omsChargerDao.findDataBySql(sql, params);
	}

	@Override
	public List<OmsCharger> findExample(OmsCharger obj, Integer pageNo, Integer pageSize, String sortName,
			Integer sortVal) {
		// return omsChargerDao.findExample(omsCharger_query, null, null, null,
		// null);
		return omsChargerDao.findExample(obj, pageNo, pageSize, sortName, sortVal);
	}

	@Override
	public OmsCharger findOneExample(OmsCharger obj, String order, String sortVal) {
		return omsChargerDao.findOneExample(obj, order, sortVal);
	}

	@Override
	public int save(OmsCharger obj) {
		return omsChargerDao.save(obj);
	}

	@Override
	public int updateStateAlternate(OmsChargerStateAlternate obj) {
		return omsChargerStateAlternateDao.updateObject(obj);
	}

	@Override
	public int updateStateDirect(OmsChargerStateDirect obj) {
		return omsChargerStateDirectDao.updateObject(obj);
	}

	@Override
	public OmsChargerStateAlternate findOneAlternate(OmsChargerStateAlternate obj, String order, String sortVal) {
		return omsChargerStateAlternateDao.findOneExample(obj, order, sortVal);
	}

	@Override
	public OmsChargerStateDirect findOneDirect(OmsChargerStateDirect obj, String order, String sortVal) {
		return omsChargerStateDirectDao.findOneExample(obj, order, sortVal);
	}

	@Override
	public int update(OmsCharger omsCharger) {
		return omsChargerDao.updateObject(omsCharger);
	}

	@Override
	public ChargerCountAndInfoVO getChargerCountAndInfo(String stationId) {

		return null;
	}

	@Override
	public List<OmsChargerStateDirect> getChargerStateInfo(String stationId) {

		return null;
	}

	// @Override
	// public JsonCommon<OmsChargerNo> getChargerStatusNo(String charger_type,
	// String ... params) {
	// String table_name = "";
	// switch (charger_type) {//1--直流 2--交流
	// case "1":
	// table_name = "oms_charger_state_direct";
	// break;
	// case "2":
	// table_name = "oms_charger_state_alternate";
	// break;
	// default:
	// return null;
	// }
	//
	// int chargerFreeNo = 0, chargerBespeakNo = 0, chargerChargeNo = 0,
	// chargerErrorNo = 0,chargerUseNo = 0,chargerSwipeNo = 0;
	// int offlineNo = 0; //修改为3.0：charge_status里包含了离线状态，不必单独读取online_status
	// //String sql_online = "select charge_status,count(charge_status) as total
	// from " + table_name+ " where valid_flag = 1 " ; //以下注释sql：原来只查单表，不关联桩表
	// String sql_online = "select b.charge_status,count(b.charge_status) as
	// total from oms_charger a," + table_name+ " b where a.charger_type = " +
	// charger_type + " and a.valid_flag = 1 and b.valid_flag=1 and
	// a.charger_id=b.charger_id " ;
	// //*******************20160405 perlin add
	// begin****************************************//
	// if(params!=null&&params.length>0){
	// //sql_online+= " and user_pay_card = '"+ params[0]+"'";
	// sql_online+= " and b.user_pay_card = '"+ params[0]+"'";
	// }
	// //*******************20160405 perlin add
	// end******************************************//
	// //sql_online += " group by charge_status";
	// sql_online += " group by b.charge_status";
	// List<Map<String, Object>> list2_a =
	// omsChargerDao.findDataBySql(sql_online);
	// if (list2_a.size() > 0) {
	// for (Map<String, Object> map : list2_a) {// 0: 空闲;1: 预约;2 充电; 3
	// 故障;4:占用中（针对双枪单充等情况）;5 刷卡中 8:离线
	// if (map.get("charge_status").toString().equals("0")) {
	// chargerFreeNo = Integer.valueOf(map.get("total").toString());
	// } else if (map.get("charge_status").toString().equals("1")) {
	// chargerBespeakNo = Integer.valueOf(map.get("total").toString());
	// } else if (map.get("charge_status").toString().equals("2")) {
	// chargerChargeNo = Integer.valueOf(map.get("total").toString());
	// } else if (map.get("charge_status").toString().equals("3")) {
	// chargerErrorNo = Integer.valueOf(map.get("total").toString());
	// } else if (map.get("charge_status").toString().equals("4")) {
	// chargerUseNo = Integer.valueOf(map.get("total").toString());
	// } else if (map.get("charge_status").toString().equals("5")) {
	// chargerSwipeNo = Integer.valueOf(map.get("total").toString());
	// }else if (map.get("charge_status").toString().equals("8")) {
	// offlineNo = Integer.valueOf(map.get("total").toString());
	// }
	// }
	// }
	// //pengyu modify 交流列表页数据问题修改 调用公用方法里面的查询当前用户是不是超级运营商管理员，不是的话就按当前运营商范围来查询
	// /*
	// * select
	// sum(case when (online_status = 1 and charge_status =0) then 1 else 0 end)
	// as status_free,
	// sum(case when (online_status = 1 and charge_status =1) then 1 else 0 end)
	// as status_bespeak,
	// sum(case when (online_status = 1 and charge_status =2) then 1 else 0 end)
	// as status_charge,
	// sum(case when (online_status = 1 and charge_status =3) then 1 else 0 end)
	// as status_error,
	// sum(case when online_status = 0 then 1 else 0 end) as status_offline ,
	// sum(1) as total
	// from oms_charger_state_alternate where valid_flag = 1 and charger_id in
	// (SELECT charger_id from oms_charger WHERE oper_merchant_id=
	// '120170857')//易充
	// * */
	//
	//
	//
	//// //String sql_offline = "select count(*) as total from " + table_name+ "
	// where online_status = 0 and valid_flag = 1 ";
	//// String sql_offline = "select count(*) as total from oms_charger a," +
	// table_name+ " b where a.charger_type = " + charger_type + " and
	// online_status = 0 and a.valid_flag = 1 and b.valid_flag=1 and
	// a.charger_id=b.charger_id ";
	//// //*******************20160405 perlin add
	// begin****************************************//
	//// if(params!=null&&params.length>0){
	//// //sql_offline+= " and user_pay_card = '"+ params[0]+"'";
	//// sql_offline+= " and b.user_pay_card = '"+ params[0]+"'";
	//// }
	//// //*******************20160405 perlin add
	// end******************************************//
	//// List<Map<String, Object>> list_offline =
	// omsChargerDao.findDataBySql(sql_offline);
	//// Map<String, Object> map_offline = list_offline.get(0);
	//// offlineNo = Integer.valueOf(map_offline.get("total").toString());
	// OmsChargerNo no = new OmsChargerNo();
	// no.setTotal(chargerFreeNo + chargerBespeakNo + chargerChargeNo +
	// chargerUseNo + chargerSwipeNo + offlineNo ); //+ chargerErrorNo
	// no.setBespeak_no(chargerBespeakNo);
	// no.setCharge_no(chargerChargeNo);
	// no.setError_no(chargerErrorNo);
	// no.setUse_no(chargerUseNo);
	// no.setSwipe_no(chargerSwipeNo);
	// no.setFree_no(chargerFreeNo);
	// no.setOffline_no(offlineNo);
	// JsonCommon<OmsChargerNo> json = new JsonCommon<OmsChargerNo>(no, "200",
	// "ok");
	// return json;
	// }

	@Override
	public JsonCommon<OmsChargerNo> getChargerStatusNo(String charger_type, String... params) {
		String table_name = "";
		switch (charger_type) {// 1--直流 2--交流
		case "1":
			table_name = "oms_charger_state_direct";
			break;
		case "2":
			table_name = "oms_charger_state_alternate";
			break;
		default:
			return null;
		}

		int chargerFreeNo = 0, chargerBespeakNo = 0, chargerChargeNo = 0, chargerErrorNo = 0, chargerUseNo = 0,
				chargerSwipeNo = 0,total = 0;
		int offlineNo = 0; // 修改为3.0：charge_status里包含了离线状态，不必单独读取online_status
		// String sql_online = "select charge_status,count(charge_status) as
		// total from " + table_name+ " where valid_flag = 1 " ;
		// //以下注释sql：原来只查单表，不关联桩表
		String sql = "select  sum(case when (online_status = 1 and charge_status =0) then 1 else 0 end) as status_free,"
				+ " sum(case when (online_status = 1 and charge_status =1) then 1 else 0 end) as status_bespeak,"
				+ " sum(case when (online_status = 1 and charge_status =2) then 1 else 0 end) as status_charge,"
				+ " sum(case when (online_status = 1 and charge_status =3) then 1 else 0 end) as status_error,"
				+ " sum(case when online_status = 0 then 1 else 0 end) as status_offline , sum(1) as total from "
				+ table_name + "  where valid_flag = 1 ";
//		if(!StringUtil.isSuperMerchant(request)){//不是超级运营商下属的管理员，就只看自己的桩
//			String oper_merchant_id = StringUtil.getUserEntityId(request);
//			if(StringUtil.isNotBlank(oper_merchant_id)){
//				sql += " and charger_id in (SELECT charger_id from oms_charger WHERE oper_merchant_id= '"+oper_merchant_id+"') ";
//			}
//		}
		
		if(!StringUtil.isSuperMerchant(request)){//不是超级运营商下属的管理员，就只看自己的桩
			log.info("getChargerStatusNo isNotSuperMerchant");
			OmsOperList user = StringUtil.getUserByRequest(request);
			String entity_id = user.getEntity_id();
			int entity_type = user.getEntity_type();
			switch(entity_type){//1：运营商；2：运营商分支机构；3：厂商；4:商户      oms_charger表中的entity_id 在用户为商户的时候才用到
			case 1:
				sql += " and charger_id in (SELECT charger_id from oms_charger WHERE oper_merchant_id= '"+entity_id+"') ";
				break;
			case 2:
				return null;
			case 3:
				return null;
			case 4:
				sql += " and charger_id in (SELECT charger_id from oms_charger WHERE entity_id= '"+entity_id+"') ";
				break;
			default:
				return null;
			}
		}
		
		if (params != null && params.length > 0) {
			// sql_online+= " and user_pay_card = '"+ params[0]+"'";
			sql += " and user_pay_card = '" + params[0] + "'";
		}
		List<Map<String, Object>> list2_a = omsChargerDao.findDataBySql(sql);
		if (list2_a.size() > 0) {
			Map<String, Object> map = list2_a.get(0);// 0: 空闲;1: 预约;2 充电; 3
														// 故障;4:占用中（针对双枪单充等情况）;5
														// 刷卡中 8:离线
			chargerFreeNo = Integer.valueOf(map.get("status_free").toString());
			chargerBespeakNo = Integer.valueOf(map.get("status_bespeak").toString());
			chargerChargeNo = Integer.valueOf(map.get("status_charge").toString());
			chargerErrorNo = Integer.valueOf(map.get("status_error").toString());
			chargerUseNo = Integer.valueOf(map.get("total").toString());
			chargerSwipeNo = Integer.valueOf(map.get("total").toString());
			offlineNo = Integer.valueOf(map.get("status_offline").toString());
			total = Integer.valueOf(map.get("total").toString());
		}
	
	// pengyu modify 交流列表页数据问题修改 调用公用方法里面的查询当前用户是不是超级运营商管理员，不是的话就按当前运营商范围来查询
	/*
	 * vand charger_id in (SELECT charger_id from oms_charger WHERE
	 * oper_merchant_id= '120170857')//易充
	 */
		OmsChargerNo no = new OmsChargerNo();
		no.setTotal(total); // 
		JsonCommon<OmsChargerNo> json = new JsonCommon<OmsChargerNo>(no, "200", "ok");
		return json;
	}

	// 按桩类型、桩地址、桩状态查询桩详情···包括桩表信息、每个充电口状态
	@Override
	public JsonForList<Map<String, Object>> getChargerStatusList(String chargerId, String charge_status,
			String charger_type, String stationId) {
		if (StringUtil.isBlank(charger_type)) {
			charger_type = "";
		}
		String state_table = "";
		switch (charger_type) {// 设备电流类型:1--直流 2--交流 3--混合
		case "1":
			state_table = "oms_charger_state_direct";
			break;
		case "2":
			state_table = "oms_charger_state_alternate";
			break;
		case "3":// 默认交流桩
			state_table = "oms_charger_state_alternate";
			break;
		default:// 默认交流桩
			state_table = "oms_charger_state_alternate";
			break;
		}

		String sql = "SELECT factory.brand,charger.charger_id,charger.station_id,charger.charger_type,charger.qr_code,charger.port_quantity,"
				+ "charger.forward_srv_id,dicforward.forward_srv_name,charger.oper_merchant_id,merchant.oper_name,charger.entity_type,charger.entity_id,charger.wifi_ap,"
				+ "charger.installation_time,charger.card_gprs,charger.card_wifi,charger.serial_no,charger.factory_id,"
				+ "charger.device_id,charger.dev_sn,charger.software_version,charger.city_code,charger.charger_ip,charger.encrypt_type,"
				+ "charger.comm_key,charger.active_flag,charger.ssid,charger.protocol_type,charger.protocol_version,"
				+ "charger.instruction_set_no,charger.rate_schema_bespeak_fee,charger.rate_schema_charge_fee,"
				+ "charger.rate_schema_service_fee,charger.fee_oper_merchant_id,charger.is_allow_generate_fee,charger.valid_flag,"
				+ "charger.review_state,charger.review_text,"
				// +
				// "charger.review_state,charger.review_text,charger.create_time,charger.create_oper_id,charger.update_time,"
				+ "charger.update_oper_id, "
				+ "station.station_name,station.district_name,factory.factory_name ,group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList "
				+ " FROM oms_charger charger inner JOIN " + state_table
				+ " state  on charger.charger_id = state.charger_id "
				+ " inner JOIN  oms_dic_forward_srv_info  dicforward  on charger.forward_srv_id = dicforward.forward_srv_id";
		sql += " LEFT JOIN oms_operation_sp_list merchant on charger.oper_merchant_id = merchant.oper_merchant_id ";
		sql += " LEFT JOIN oms_station station on charger.station_id = station.station_id ";
		if (StringUtil.isNotBlank(stationId)) {
			sql += " and station.station_id = '" + stationId + "'";
		}
		sql += " LEFT JOIN  oms_factory_list factory ON charger.factory_id = factory.factory_id where charger.valid_flag = 1 ";
		if (StringUtil.isNotBlank(charge_status)) {
			sql += " and state.charge_status = " + charge_status;
		}
		if (StringUtil.isNotBlank(chargerId)) {
			sql += " and charger.charger_id = '" + chargerId + "'";
		}
		// sql += " GROUP BY charger.charger_id";

		// + "from oms_charger charger,"+state_table+" state,oms_station
		// station,oms_factory_list factory "
		// + "where charger.charger_id = state.charger_id and charger.station_id
		// = station.station_id and charger.factory_id =factory.factory_id ";
		// if(StringUtil.isNotBlank(charge_status)){
		// sql += " and state.charge_status = "+charge_status;
		// }if(StringUtil.isNotBlank(chargerId)){
		// sql += " and charger.charger_id = '"+chargerId+"'";
		// }
		sql += " group by charger.charger_id ";
		List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(sql);
		// List<OmsCharger> chargerList = new ArrayList<OmsCharger>();
		return new JsonForList<>(list_map, "200", "ok");
		// for(Map<String, Object> map: list_map){
		// OmsCharger charger = new OmsCharger();
		// charger.setCharger_id(map.get("charger_id").toString());
		// chargerList.add(charger);
		// }

		// String sql_offline = "select count(*) as total from
		// oms_charger_state_alternate where online_status = 0";
		// List<Map<String, Object>> list_offline = findDataBySql(sql_offline,
		// null);
		// Map<String, Object> map_offline = list_offline.get(0);
		// offlineNo = Integer.valueOf(map_offline.get("total").toString());

		// return new JsonForList<>(chargerList, "200", "ok");

	}

	/******************** 20160325 perlin add begin ***************************/
	@Override
	public OmsCharger findChargerDetailByQrCode(String qr_code) {
		String conditionSql = " a left join (select b.factory_id other_factory_id, b.factory_name"
				+ " from oms_factory_list b) fact_view on fact_view.other_factory_id=a.factory_id" + "  LEFT JOIN"
				+ " (select d.city_code other_city_code,d.city_name from oms_dic_city_code d) city_view on city_view.other_city_code=a.city_code "
				+ " where qr_code ='" + qr_code + "'";
		OmsCharger queryCharge = new OmsCharger();
		queryCharge.setQr_code(qr_code);
		List<OmsCharger> lsOmsCharger = this.omsChargerDao.findListByConditionWithIgnore(queryCharge, conditionSql);
		if (lsOmsCharger != null && lsOmsCharger.size() > 0) {
			return lsOmsCharger.get(0);
		} else {
			return null;
		}
	}

	@Override
	public OmsCharger findChargerDetailByChargerId(String charger_id) {
		String conditionSql = " a left join (select b.factory_id other_factory_id, b.factory_name"
				+ " from oms_factory_list b) fact_view on fact_view.other_factory_id=a.factory_id" + "  LEFT JOIN"
				+ " (select d.city_code other_city_code,d.city_name from oms_dic_city_code d) city_view on city_view.other_city_code=a.city_code "
				+ " where charger_id ='" + charger_id + "'";
		OmsCharger queryCharge = new OmsCharger();
		queryCharge.setCharger_id(charger_id);
		List<OmsCharger> lsOmsCharger = this.omsChargerDao.findListByConditionWithIgnore(queryCharge, conditionSql);
		if (lsOmsCharger != null && lsOmsCharger.size() > 0) {
			return lsOmsCharger.get(0);
		} else {
			return null;
		}
	}

	@Override
	public Long getFreeChargerByStationId(String station_id, int type) {
		// String sql = "select count(1) free_Chargers_count from oms_charger
		// where station_id='"+station_id+"'";
		// if(type==1){
		// sql += " and charger_id not in ( select distinct charger_id from
		// oms_charger_state_alternate where charge_status=2) ";
		// }
		// else{
		// sql += " and charger_id not in ( select distinct charger_id from
		// oms_charger_state_direct where charge_status=2)";
		// }
		String sql = "select count(1) free_Chargers_count from oms_charger a,";
		if (type == 1) {
			sql += " oms_charger_state_direct ";
		} else {
			sql += "  oms_charger_state_alternate ";
		}
		sql += " b where a.valid_flag=1 and a.station_id='" + station_id + "' and a.charger_type=" + type
				+ " and a.charger_id=b.charger_id and b.charge_status=0";
		Long retCounts = 0l;
		List<Map<String, Object>> retListMap = this.omsChargerDao.findDataBySql(sql, null);
		if (retListMap != null && retListMap.size() > 0) {
			retCounts = (Long) retListMap.get(0).get("free_Chargers_count");

		}
		return retCounts;
	}

	@Override
	public <T> List<T> getPortsStateInfo(String chargerId) {
		OmsCharger charger = this.findChargerDetailByChargerId(chargerId);
		if (charger.getCharger_type() == 2) {
			OmsChargerStateAlternate queryObj = new OmsChargerStateAlternate();
			queryObj.setCharger_id(chargerId);
			List lsOmsChargerStateAlert = this.omsChargerStateAlternateDao.findListByCondition(queryObj,
					" where charger_id='" + chargerId + "'");
			return lsOmsChargerStateAlert;
		} else {
			OmsChargerStateDirect queryObj = new OmsChargerStateDirect();
			queryObj.setCharger_id(chargerId);
			List lsOmsChargerStateDirect = this.omsChargerStateDirectDao.findListByCondition(queryObj,
					" where charger_id='" + chargerId + "'");
			return lsOmsChargerStateDirect;
		}
	}

	@Override
	public JsonCommon getPortStateInfo(String chargerId, String port_no) throws Exception {
		log.info("getPortStateInfo chargerId:" + chargerId + " port_no:" + port_no);
		OmsCharger charger = this.findChargerDetailByChargerId(chargerId);
		JsonCommon retJson = new JsonCommon(MsgCodeEnum.SUCCESS.getMsgCode(), MsgCodeEnum.SUCCESS.getMsgInfo());
		if (charger.getCharger_type() == 2) { // 设备电流类型:1--直流 2--交流 3--混合
			OmsChargerStateAlternate queryObj = new OmsChargerStateAlternate();
			queryObj.setCharger_id(chargerId);
			queryObj.setPort_no(Integer.valueOf(port_no));
			queryObj.setValid_flag(1);
			OmsChargerStateAlternate state = this.omsChargerStateAlternateDao.findOneExample(queryObj, null, null);
			if (state == null)
				throw new Exception("No record found");

			// 如果1.X的桩有预约的话，由于异常回滚需要，枪口状态表中Bespeak_jrnl的值是预约记录表中的Oms_msg_bespeak_jrnl；因此需要转换回预约记录表中的Bespeak_jrnl的值
			if (StringUtil.isNotBlank(state.getBespeak_jrnl())) {
				if (StringUtil.isNotBlank(charger.getProtocol_version())
						&& ("0101".equals(charger.getProtocol_version()) || "0102".equals(charger.getProtocol_version())
								|| "0103".equals(charger.getProtocol_version()))) {
					OmsChargerBespeakBillRecord bespeakBillQuery = new OmsChargerBespeakBillRecord();
					bespeakBillQuery.setOms_msg_bespeak_jrnl(state.getBespeak_jrnl());
					bespeakBillQuery.setCharger_id(state.getCharger_id());
					OmsChargerBespeakBillRecord bespeakBill = bespeakBillRecordDao.findOneExample(bespeakBillQuery,
							null, null);
					if (bespeakBill != null) {
						state.setBespeak_jrnl(bespeakBill.getBespeak_jrnl());
					}
				}
			}

			// 如果充电中，才取充电状态数据
			if (state.getCharge_status() == 2) {
				String key_charging = chargerId + String.format("%02d", Integer.valueOf(port_no)) + "_status";
				Jedis jedis = RedisClient.getConnect();
				String json = jedis.get(key_charging);
				log.info("getPortStateInfo key_charging:" + key_charging);
				ChargeDataUploadingVO vo = null;
				if (StringUtil.isNotBlank(json)) {
					log.info("getPortStateInfo JSON from redis:" + json.toString());
					vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
					state.setCharger_v(Float.valueOf(vo.getCharger_v()));
					state.setCharger_i(Float.valueOf(vo.getCharger_i()));
					state.setCharger_p(Float.valueOf(vo.getCharger_p()));
					state.setCharger_minute(Float.valueOf(vo.getCharger_time()));
					state.setCharger_kwh(Float.parseFloat(vo.getCharger_kwh()));
					state.setCharger_fee(Float.parseFloat(vo.getCharger_fee()));
					state.setSoc(vo.getSoc());
				}
				jedis.close();
			}

			retJson.setPojo(state);
			log.info("getPortStateInfo retJson:" + retJson.toString());
			return retJson;
		} else {
			OmsChargerStateDirect queryObj = new OmsChargerStateDirect();
			queryObj.setCharger_id(chargerId);
			queryObj.setPort_no(Integer.valueOf(port_no));
			queryObj.setValid_flag(1);
			OmsChargerStateDirect state = this.omsChargerStateDirectDao.findOneExample(queryObj, null, null);
			if (state == null)
				throw new Exception("No record found");

			// 如果1.X的桩有预约的话，由于异常回滚需要，枪口状态表中Bespeak_jrnl的值是预约记录表中的Oms_msg_bespeak_jrnl；因此需要转换回预约记录表中的Bespeak_jrnl的值
			if (StringUtil.isNotBlank(state.getBespeak_jrnl())) {
				if (StringUtil.isNotBlank(charger.getProtocol_version())
						&& ("0101".equals(charger.getProtocol_version()) || "0102".equals(charger.getProtocol_version())
								|| "0103".equals(charger.getProtocol_version()))) {
					OmsChargerBespeakBillRecord bespeakBillQuery = new OmsChargerBespeakBillRecord();
					bespeakBillQuery.setOms_msg_bespeak_jrnl(state.getBespeak_jrnl());
					bespeakBillQuery.setCharger_id(state.getCharger_id());
					OmsChargerBespeakBillRecord bespeakBill = bespeakBillRecordDao.findOneExample(bespeakBillQuery,
							null, null);
					if (bespeakBill != null) {
						state.setBespeak_jrnl(bespeakBill.getBespeak_jrnl());
					}
				}
			}

			// 如果充电中，才取充电状态数据
			if (state.getCharge_status() == 2) {
				String key_charging = chargerId + String.format("%02d", Integer.valueOf(port_no)) + "_status";
				log.info("getPortStateInfo key_charging:" + key_charging);
				Jedis jedis = RedisClient.getConnect();
				String json = jedis.get(key_charging);
				ChargeDataUploadingVO vo = null;
				if (StringUtil.isNotBlank(json)) {
					log.info("getPortStateInfo JSON from redis:" + json.toString());
					vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
					state.setCharger_v(Float.valueOf(vo.getCharger_v()));
					state.setCharger_i(Float.valueOf(vo.getCharger_i()));
					state.setCharger_p(Float.valueOf(vo.getCharger_p()));
					state.setCharger_minute(Float.valueOf(vo.getCharger_time()));
					state.setCharger_kwh(Float.parseFloat(vo.getCharger_kwh()));
					state.setCharger_fee(Float.parseFloat(vo.getCharger_fee()));
					state.setSoc(vo.getSoc());
					log.info("soc ======== " + vo.getSoc());
				} else {
					log.info("getPortStateInfo JSON from redis: null!" + key_charging);
				}
				jedis.close();
			}

			retJson.setPojo(state);
			log.info("getPortStateInfo retJson:" + retJson.toString());
			return retJson;
		}
	}

	/******************** 20160325 perlin add end ***************************/

	@Override
	public JsonForList<OmsCharger> getChargersWithOutStationByOperMerchantId(String oper_merchant_id) {
		String condition = " where valid_flag = 1 and (station_id is null or length(trim(station_id))<1) and oper_merchant_id ='"
				+ oper_merchant_id + "'";
		List<OmsCharger> list = omsChargerDao.findListByCondition(new OmsCharger(), condition);
		return new JsonForList<>(list, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
				OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@Override
	public JsonForList getChargersDetailByStationId(String station_id) {
		StringBuilder sb = new StringBuilder("");
		// 交流桩
		sb.append(
				"SELECT factory.brand,charger.charger_id,charger.station_id,charger.charger_type,charger.qr_code,charger.port_quantity,"
						+ "charger.forward_srv_id,charger.oper_merchant_id,charger.entity_type,charger.entity_id,charger.wifi_ap,"
						+ "charger.installation_time,charger.card_gprs,charger.card_wifi,charger.serial_no,charger.factory_id,"
						+ "charger.device_id,charger.dev_sn,charger.software_version,charger.city_code,charger.charger_ip,charger.encrypt_type,"
						+ "charger.comm_key,charger.active_flag,charger.ssid,charger.protocol_type,charger.protocol_version,"
						+ "charger.instruction_set_no,charger.rate_schema_bespeak_fee,charger.rate_schema_charge_fee,"
						+ "charger.rate_schema_service_fee,charger.fee_oper_merchant_id,charger.is_allow_generate_fee,charger.valid_flag,"
						+ "charger.review_state,charger.review_text,"
						// +
						// "charger.review_state,charger.review_text,charger.create_time,charger.create_oper_id,charger.update_time,"
						+ "charger.update_oper_id, "
						+ "station.station_name,station.district_name,factory.factory_name ,group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList "
						+ " FROM oms_charger charger inner JOIN oms_charger_state_alternate state  on charger.charger_id = state.charger_id "
						+ " LEFT JOIN oms_station station on charger.station_id = station.station_id "
						+ " and station.station_id = '" + station_id + "'" + " group by charger.charger_id ");
		sb.append(" union all ");
		// 直流桩
		sb.append(
				"SELECT factory.brand,charger.charger_id,charger.station_id,charger.charger_type,charger.qr_code,charger.port_quantity,"
						+ "charger.forward_srv_id,charger.oper_merchant_id,charger.entity_type,charger.entity_id,charger.wifi_ap,"
						+ "charger.installation_time,charger.card_gprs,charger.card_wifi,charger.serial_no,charger.factory_id,"
						+ "charger.device_id,charger.dev_sn,charger.software_version,charger.city_code,charger.charger_ip,charger.encrypt_type,"
						+ "charger.comm_key,charger.active_flag,charger.ssid,charger.protocol_type,charger.protocol_version,"
						+ "charger.instruction_set_no,charger.rate_schema_bespeak_fee,charger.rate_schema_charge_fee,"
						+ "charger.rate_schema_service_fee,charger.fee_oper_merchant_id,charger.is_allow_generate_fee,charger.valid_flag,"
						+ "charger.review_state,charger.review_text,"
						// +
						// "charger.review_state,charger.review_text,charger.create_time,charger.create_oper_id,charger.update_time,"
						+ "charger.update_oper_id, "
						+ "station.station_name,station.district_name,factory.factory_name ,group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList "
						+ " FROM oms_charger charger inner JOIN oms_charger_state_direct state  on charger.charger_id = state.charger_id "
						+ " LEFT JOIN oms_station station on charger.station_id = station.station_id "
						+ " and station.station_id = '" + station_id + "'" + " group by charger.charger_id ");
		List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(sb.toString());
		// List<OmsCharger> chargerList = new ArrayList<OmsCharger>();
		return new JsonForList<>(list_map, "200", "ok");
	}

	@Override
	public JsonCommon<OmsCharger> getLists(OmsCharger charger, String qr_code) {
		JsonCommon<OmsCharger> retJsons = new JsonCommon<>();
		OmsCharger list = omsChargerDao.findOneExampleByCondition(charger,
				"where qr_code='" + qr_code + "' and valid_flag=1");
		if (list == null || "".equals(list)) {
			retJsons.setCode(MsgCodeEnum.ERROR400.getMsgCode());
			retJsons.setMsg(MsgCodeEnum.ERROR400.getMsgInfo());
		} else {
			retJsons.setPojo(list);
			retJsons.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			retJsons.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
		}
		return retJsons;
	}

	@Override
	public JsonForList<Map<String, Object>> getSimpleChargerList(String stationId, String charger_type,
			String chargerId) {
		StringBuilder sb = new StringBuilder(
				"select charger.charger_id,charger.serial_no,charger.qr_code,charger.charger_type,station.station_name,station.district_name,");
		sb.append("group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList");
		if (StringUtil.isNotBlank(stationId)) {// 不管后面的参数
			sb.append(
					" FROM oms_charger charger inner JOIN oms_charger_state_direct state  on charger.charger_id = state.charger_id and charger.valid_flag = 1 "); // 获取站所属桩时，取有效桩
			sb.append(
					" inner JOIN oms_station station  on charger.station_id = station.station_id and charger.station_id = '"
							+ stationId + "'");
			sb.append(" GROUP BY charger.charger_id  ");
			sb.append(" union all ");
			sb.append(
					" select charger.charger_id,charger.serial_no,charger.qr_code,charger.charger_type,station.station_name,station.district_name,");
			sb.append(" group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList");
			sb.append(
					" FROM oms_charger charger inner JOIN oms_charger_state_alternate state  on charger.charger_id = state.charger_id and charger.valid_flag = 1 "); // 获取站所属桩时，取有效桩
			sb.append(
					" inner JOIN oms_station station  on charger.station_id = station.station_id and charger.station_id = '"
							+ stationId + "'");
			sb.append(" GROUP BY charger.charger_id  ");
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(sb.toString());
			return new JsonForList<>(list_map, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
					OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		}
		String entityId = StringUtil.getUserEntityId(request);
		Boolean isSuper = StringUtil.isSuperMerchant(request);
		String state_table = "";
		if (StringUtil.isNotBlank(charger_type)) {// 不管后面的参数
			switch (charger_type) {// 设备电流类型:1--直流 2--交流 3--混合
			case "1":
				// state_table ="oms_charger_state_direct";
				sb.append(
						" FROM (select  *  from oms_charger where charger_type=1 and valid_flag=1) charger LEFT JOIN oms_charger_state_direct state  on charger.charger_id = state.charger_id and ");
				break;
			case "2":
				// state_table ="oms_charger_state_alternate";
				sb.append(
						" FROM (select *  from oms_charger where charger_type=2 and valid_flag=1) charger LEFT JOIN oms_charger_state_alternate state  on charger.charger_id = state.charger_id");

				break;
			default:
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ParamValueError.value(),
						OmsConstant.ErrorCodeEnum.ParamValueError.desc());
			}
			log.info("entityId = " + entityId);
			log.info("isSuper = " + isSuper);
			if (entityId != null && isSuper == false) {
				sb.append(" and charger.oper_merchant_id = '" + entityId + "'");
			}

			// sb.append(" FROM oms_charger charger inner JOIN "+state_table+"
			// state on charger.charger_id = state.charger_id");
			sb.append(" LEFT JOIN oms_station station  on charger.station_id = station.station_id");
			sb.append(" GROUP BY charger.charger_id  ");
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(sb.toString());
			log.info(" getSimpleChargerList " + sb.toString());
			return new JsonForList<>(list_map, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
					OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		}
		if (StringUtil.isNotBlank(chargerId)) {
			OmsCharger charger = omsChargerDao.findOneExample(new OmsCharger(chargerId), null, null);
			if (charger == null || charger.getCharger_type() == null) {
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
						OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
			}
			switch (charger.getCharger_type()) {// 设备电流类型:1--直流 2--交流 3--混合
			case 1:
				state_table = "oms_charger_state_direct";
				break;
			case 2:
				state_table = "oms_charger_state_alternate";
				break;
			default:
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ParamValueError.value(),
						OmsConstant.ErrorCodeEnum.ParamValueError.desc());
			}
			sb.append(" FROM oms_charger charger inner JOIN " + state_table
					+ " state  on charger.charger_id = state.charger_id");
			sb.append(" inner JOIN oms_station station  on charger.station_id = station.station_id");
			sb.append(" WHERE charger.valid_flag = 1 and charger.charger_id = '" + chargerId + "'");
			sb.append(" GROUP BY charger.charger_id  ");
			log.info(" getSimpleChargerList " + sb.toString());
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(sb.toString());
			return new JsonForList<>(list_map, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
					OmsConstant.SuccessCodeEnum.SuccessCode.desc());

		}
		return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.MissParam.value(),
				OmsConstant.ErrorCodeEnum.MissParam.desc());
	}

	@Override
	public JsonForList<Map<String, Object>> getSimpleChargerPageList(OmsCommonParam buildQueryParam, String stationId,
			String charger_type, String chargerId, String chargerStatus, String searchStr) {
		StringBuilder selectStr = new StringBuilder(
				"select charger.charger_id,charger.serial_no,charger.qr_code,charger.charger_type,station.station_name,station.district_name,");
		selectStr.append("group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList");
		selectStr.append(",group_concat(state.online_status Order BY  state.port_no ASC) as chargeOnLineStatusList ");
		StringBuilder countStr = new StringBuilder("select count(1) from ( ");
		// StringBuilder conditionStr = new StringBuilder("");
		if (StringUtil.isNotBlank(stationId)) {// 不管后面的参数
			selectStr.append(
					" FROM oms_charger charger inner JOIN oms_charger_state_direct state  on charger.charger_id = state.charger_id and charger.valid_flag = 1 "); // 获取站所属桩时，取有效桩
			selectStr
					.append(" inner JOIN oms_station station  on charger.station_id = station.station_id and charger.station_id = '"
							+ stationId + "'");
			selectStr.append(" GROUP BY charger.charger_id  ");
			selectStr.append(" union all ");
			selectStr.append(
					" select charger.charger_id,charger.serial_no,charger.qr_code,charger.charger_type,station.station_name,station.district_name,");
			selectStr.append(" group_concat(state.charge_status Order BY  state.port_no ASC) as chargeStatusList");
			selectStr.append(
					" FROM oms_charger charger inner JOIN oms_charger_state_alternate state  on charger.charger_id = state.charger_id and charger.valid_flag = 1 "); // 获取站所属桩时，取有效桩
			selectStr
					.append(" inner JOIN oms_station station  on charger.station_id = station.station_id and charger.station_id = '"
							+ stationId + "'");
			selectStr.append(" GROUP BY charger.charger_id  ");
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(selectStr.toString());
			return new JsonForList<>(list_map, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
					OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		}
		String state_table = "";
		if (StringUtil.isNotBlank(charger_type)) {// 不管后面的参数
			switch (charger_type) {// 设备电流类型:1--直流 2--交流 3--混合
			case "1":
				// state_table ="oms_charger_state_direct";
				selectStr.append(
						" FROM oms_charger charger INNER JOIN oms_charger_state_direct state  on charger.charger_id = state.charger_id");
				break;
			case "2":
				// state_table ="oms_charger_state_alternate";
				selectStr.append(
						" FROM oms_charger charger INNER JOIN oms_charger_state_alternate state  on charger.charger_id = state.charger_id");
				break;
			default:
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ParamValueError.value(),
						OmsConstant.ErrorCodeEnum.ParamValueError.desc());
			}

//			String entityId = StringUtil.getUserEntityId(request);
//			Boolean isSuper = StringUtil.isSuperMerchant(request);
//			log.info("entityId = " + entityId);
//			log.info("isSuper = " + isSuper);
//			if (entityId != null && isSuper == false) {
//				selectStr.append(" and charger.oper_merchant_id = '" + entityId + "'");
//			}
			
			if(!StringUtil.isSuperMerchant(request)){//不是超级运营商下属的管理员，就只看自己的桩
				OmsOperList user = StringUtil.getUserByRequest(request);
				String entity_id = user.getEntity_id();
				int entity_type = user.getEntity_type();
				switch(entity_type){//1：运营商；2：运营商分支机构；3：厂商；4:商户      oms_charger表中的entity_id 在用户为商户的时候才用到
				case 1:
					selectStr.append(" and charger.oper_merchant_id = '" + entity_id + "' ");
					break;
				case 2:
					return null;
				case 3:
					return null;
				case 4:
					selectStr.append(" and charger.entity_id = '" + entity_id + "' ");
					break;
				default:
					return null;
				}
			}
			

			selectStr
					.append(" LEFT JOIN oms_station station  on charger.station_id = station.station_id WHERE charger.charger_type = ")
					.append(charger_type).append(" AND charger.valid_flag = 1 ");
			selectStr.append(" GROUP BY charger.charger_id  ");

			selectStr = new StringBuilder("select *  from (").append(selectStr.append(") a where 1=1").toString());

			if (StringUtil.isNotBlank(chargerStatus)) {
				selectStr = selectStr.append(" and a.chargeStatusList like '%").append(chargerStatus).append("%'");
			}
			if (StringUtil.isNotBlank(searchStr)) {
				selectStr = selectStr.append(" and (a.charger_id like '%").append(searchStr)
						.append("%' or a.serial_no like '%").append(searchStr).append("%' or a.station_name like '%")
						.append(searchStr).append("%' or a.qr_code like '%").append(searchStr)
						.append("%' or a.district_name like '%").append(searchStr)
						.append("%' or a.chargeStatusList like '%").append(searchStr).append("%')");
			}

			int total = 0;
			if (buildQueryParam.isQueryTotal()) {
				try {
					total = omsChargerDao.queryTotalBySql(new OmsCharger(),
							countStr.toString() + selectStr.toString() + ") b", new ArrayList<Object>());
				} catch (Exception e) {
					total = 0;
					e.printStackTrace();
				}
			}

			// 分页查询匹配
			if (buildQueryParam.getPageNo() != null && buildQueryParam.getPageSize() != null
					&& buildQueryParam.getPageSize().intValue() != 0) {
				selectStr.append(" limit ");
				selectStr.append((buildQueryParam.getPageNo() - 1) * buildQueryParam.getPageSize());
				selectStr.append(",");
				selectStr.append(buildQueryParam.getPageSize());
			}
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(selectStr.toString());

			JsonPageForList jfl = new JsonPageForList();
			jfl.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			jfl.setList(list_map);
			jfl.setTotal(total);
			jfl.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			return jfl;
		}
		if (StringUtil.isNotBlank(chargerId)) {
			// 按chargerId查询，就只有一条结果，不需要提供查询接口
			OmsCharger charger = omsChargerDao.findOneExample(new OmsCharger(chargerId), null, null);
			if (charger == null || charger.getCharger_type() == null) {
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
						OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
			}
			switch (charger.getCharger_type()) {// 设备电流类型:1--直流 2--交流 3--混合
			case 1:
				state_table = "oms_charger_state_direct";
				break;
			case 2:
				state_table = "oms_charger_state_alternate";
				break;
			default:
				return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.ParamValueError.value(),
						OmsConstant.ErrorCodeEnum.ParamValueError.desc());
			}
			selectStr.append(" FROM oms_charger charger inner JOIN " + state_table
					+ " state  on charger.charger_id = state.charger_id");
			selectStr.append(" inner JOIN oms_station station  on charger.station_id = station.station_id");
			selectStr.append(" WHERE charger.valid_flag = 1 and charger.charger_id = '" + chargerId + "'");
			selectStr.append(" GROUP BY charger.charger_id  ");

			int total = 0;
			if (buildQueryParam.isQueryTotal()) {
				try {
					total = omsChargerDao.queryTotalBySql(new OmsCharger(),
							countStr.toString() + selectStr.toString() + ") a", new ArrayList<Object>());
				} catch (Exception e) {
					total = 0;
					e.printStackTrace();
				}
			}

			// 分页查询匹配
			if (buildQueryParam.getPageNo() != null && buildQueryParam.getPageSize() != null
					&& buildQueryParam.getPageSize().intValue() != 0) {
				selectStr.append(" limit ");
				selectStr.append((buildQueryParam.getPageNo() - 1) * buildQueryParam.getPageSize());
				selectStr.append(",");
				selectStr.append(buildQueryParam.getPageSize());
			}
			List<Map<String, Object>> list_map = omsChargerDao.findDataBySql(selectStr.toString());

			JsonPageForList jfl = new JsonPageForList();
			jfl.setCode(MsgCodeEnum.SUCCESS.getMsgCode());
			jfl.setList(list_map);
			jfl.setTotal(total);
			jfl.setMsg(MsgCodeEnum.SUCCESS.getMsgInfo());
			return jfl;

		}
		return new JsonForList<>(null, OmsConstant.ErrorCodeEnum.MissParam.value(),
				OmsConstant.ErrorCodeEnum.MissParam.desc());
	}

	@Override
	public String getQrCode(String charger_id) {
		if (charger_id == null)
			throw new NullPointerException("charger id is null");
		OmsCharger c = new OmsCharger();
		c.setCharger_id(charger_id);
		OmsCharger charger = omsChargerDao.findOneExample(c, null, null);
		String qrcode = null;
		if (charger != null)
			qrcode = charger.getQr_code();
		return qrcode;
	}

	@Override
	public OmsChargerBespeakBillRecord getChargerBespeakBill(String charger_id, Integer charger_port_no,
			String user_pay_card) {
		OmsChargerBespeakBillRecord omsChargerBespeakBillRecord = new OmsChargerBespeakBillRecord();
		omsChargerBespeakBillRecord.setCharger_id(charger_id);
		omsChargerBespeakBillRecord.setPort_no(charger_port_no);
		omsChargerBespeakBillRecord.setUser_pay_card(user_pay_card);

		omsChargerBespeakBillRecord = bespeakBillRecordDao.findOneExample(omsChargerBespeakBillRecord, "start_time",
				"desc");
		return omsChargerBespeakBillRecord;
	}

	@Override
	public OmsChargerChargeBillRecord getChargerChargeBill(String charger_id, Integer charger_port_no,
			String user_pay_card) {
		OmsChargerChargeBillRecord omsChargerChargeBillRecord = new OmsChargerChargeBillRecord();
		omsChargerChargeBillRecord.setCharger_id(charger_id);
		omsChargerChargeBillRecord.setPort_no(charger_port_no);
		omsChargerChargeBillRecord.setUser_pay_card(user_pay_card);

		omsChargerChargeBillRecord = chargeBillRecordDao.findOneExample(omsChargerChargeBillRecord, "start_time",
				"desc");
		return omsChargerChargeBillRecord;
	}

	@Override
	public JsonCommon getChargeInfoAndBespeakInfoByUserPayCard(String user_pay_card) {
		// StringBuilder sb = new StringBuilder("select * from ( ");
		// sb.append("select 'bespeak'
		// type,a.charger_id,a.port_no,b.address,b.station_name ");
		// sb.append("from oms_charger_bespeak_bill_record a,oms_station b ");
		// sb.append("where a.status='1' and a.valid_flag='1' and
		// a.station_id=b.station_id ");
		// sb.append("and a.user_pay_card = ? ");
		// sb.append("order by a.start_time desc ");
		// sb.append("limit 1) t1 ");
		// sb.append("union ");
		// sb.append("select * from ( ");
		// sb.append("select 'charge'
		// type,c.charger_id,c.port_no,d.address,d.station_name ");
		// sb.append("from oms_charger_charge_bill_record c,oms_station d ");
		// sb.append("where c.status='1' and c.valid_flag='1' and
		// c.station_id=d.station_id ");
		// sb.append("and c.user_pay_card = ? ");
		// sb.append("order by c.start_time desc ");
		// sb.append("limit 1) t2 ");
		// List<Map<String, Object>> list_map =
		// omsChargerDao.findDataBySql(sb.toString(), user_pay_card);
		// 预约查询状态为2
		StringBuilder condition = new StringBuilder("where status='2' and valid_flag='1' and user_pay_card='"
				+ user_pay_card + "' order by start_time desc");
		List<OmsChargerBespeakBillRecord> listBespeak = bespeakBillRecordDao
				.findListByCondition(new OmsChargerBespeakBillRecord(), condition.toString());
		// 充电查询查询状态为1
		condition = new StringBuilder("where status='1' and valid_flag='1' and user_pay_card='" + user_pay_card
				+ "' order by start_time desc");
		List<OmsChargerChargeBillRecord> listCharge = chargeBillRecordDao
				.findListByCondition(new OmsChargerChargeBillRecord(), condition.toString());

		JsonCommon<Map<String, Object>> retJson = new JsonCommon<Map<String, Object>>(MsgCodeEnum.SUCCESS.getMsgCode(),
				MsgCodeEnum.SUCCESS.getMsgInfo());

		Map<String, Object> retMap = new HashMap<String, Object>();
		if (listBespeak.size() > 0) {
			retMap.put("bespeak", listBespeak);
		}
		if (listCharge.size() > 0) {
			retMap.put("charge", listCharge);
		}
		retJson.setPojo(retMap);

		return retJson;
	}

	@Override
	public JsonCommon getBespeakDetailInfoByOrderNo(String order_no) {
		StringBuilder condition = new StringBuilder(
				"where valid_flag='1' and order_no='" + order_no + "' order by start_time desc");
		List<OmsChargerBespeakBillRecord> listBespeak = bespeakBillRecordDao
				.findListByCondition(new OmsChargerBespeakBillRecord(), condition.toString());
		JsonCommon<Map<String, Object>> retJson = new JsonCommon<Map<String, Object>>(MsgCodeEnum.SUCCESS.getMsgCode(),
				MsgCodeEnum.SUCCESS.getMsgInfo());

		Map<String, Object> retMap = new HashMap<String, Object>();
		if (listBespeak.size() > 0) {
			OmsChargerBespeakBillRecord bespeakBillRecord = listBespeak.get(0);

			condition = new StringBuilder(
					"where valid_flag='1' and charger_id='" + bespeakBillRecord.getCharger_id() + "'");
			OmsCharger omsCharger = omsChargerDao.findOneExampleByCondition(new OmsCharger(), condition.toString());

			condition = new StringBuilder(
					"where valid_flag='1' and station_id='" + bespeakBillRecord.getStation_id() + "'");
			OmsStation omsStation = omsStationDao.findOneExampleByCondition(new OmsStation(), condition.toString());

			retMap.put("bespeak", bespeakBillRecord);
			retMap.put("station", omsStation);
			retMap.put("charger", omsCharger);
		}
		retJson.setPojo(retMap);

		return retJson;
	}

	@Override
	public JsonCommon getChargeDetailInfoByOrderNo(String order_no) {
		StringBuilder condition = new StringBuilder(
				"where valid_flag='1' and order_no='" + order_no + "' order by start_time desc");
		List<OmsChargerChargeBillRecord> listCharge = chargeBillRecordDao
				.findListByCondition(new OmsChargerChargeBillRecord(), condition.toString());
		JsonCommon<Map<String, Object>> retJson = new JsonCommon<Map<String, Object>>(MsgCodeEnum.SUCCESS.getMsgCode(),
				MsgCodeEnum.SUCCESS.getMsgInfo());

		Map<String, Object> retMap = new HashMap<String, Object>();
		if (listCharge.size() > 0) {
			OmsChargerChargeBillRecord chargeBillRecord = listCharge.get(0);

			condition = new StringBuilder(
					"where valid_flag='1' and charger_id='" + chargeBillRecord.getCharger_id() + "'");
			OmsCharger omsCharger = omsChargerDao.findOneExampleByCondition(new OmsCharger(), condition.toString());

			condition = new StringBuilder(
					"where valid_flag='1' and station_id='" + chargeBillRecord.getStation_id() + "'");
			OmsStation omsStation = omsStationDao.findOneExampleByCondition(new OmsStation(), condition.toString());

			retMap.put("charge", chargeBillRecord);
			retMap.put("station", omsStation);
			retMap.put("charger", omsCharger);
		}
		retJson.setPojo(retMap);

		return retJson;
	}

	@Override
	public JsonCommon getChargeStateForBigScreenByIds(String chargerIds) {
		String[] list = chargerIds.split(",");
		if (list.length <= 0) {
			return new JsonCommon(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
					OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
		}
		ScreenCharger sc = new ScreenCharger();
		List stateList = new ArrayList<>();
		for (String chargerId : list) {
			OmsCharger charger = omsChargerDao.findOneExample(new OmsCharger(chargerId), null, null);
			if (charger == null || charger.getCharger_type() == null) {
				return new JsonCommon(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
						OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc() + ":" + chargerId);
			} else if (charger != null && charger.getCharger_type() != null) {
				if (sc.getCharger_type() <= 0) {
					sc.setCharger_type(charger.getCharger_type());
				}
				switch (charger.getCharger_type()) {// 1直流 2 交流
				case 1:
					// 查询 6.12电池信息上送（可选）当前荷电状态 BIN码 1 系数为1% 0-100% 从redis中取得
					OmsChargerStateDirect direct_query = new OmsChargerStateDirect();
					direct_query.setCharger_id(chargerId);
					direct_query.setPort_no(1);
					// 肯定是直流桩，所以查询 oms_charger_state_direct[直流充电桩状态表]
					List<OmsChargerStateDirect> list_direct = omsChargerStateDirectDao.findExample(direct_query, null,
							null, null, null);
					if (list_direct == null || list_direct.size() == 0) {
						return new JsonCommon(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
								OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
					}
					// 电压 功率 电流 SOC 从redis中取得
					// list.size() = 2 是预期查询结果
					// 已充电量 预计剩余时间 从6.10充电状态上送 中取得； 最高动力电池温度 BIN码 1 系数为1 偏移50
					// -50到200度 从 6.12电池信息上送（可选） 中取得
					// 电压 功率 电流 SOC 从从6.10充电状态上送 中取得；
					for (OmsChargerStateDirect state : list_direct) {
						if (state.getCharge_status() == 2) {
							String oms_msg_charge_jrnl = "";
							String battery_temperature = "";// 温度
							// 查询当前最新的充电流水号，通过charger_id端口号
							int port_no = state.getPort_no();

							String key_charging = chargerId + String.format("%02d", port_no) + "_status";
							Jedis redisClient = RedisClient.getConnect();

							String json = redisClient.get(key_charging);
							redisClient.close();

							if (json != null) {
								ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
								if (charging_vo != null) {
									state.setSoc(charging_vo.getSoc());
									state.setCharger_kwh(Float.valueOf(charging_vo.getCharger_kwh()));
									state.setCharger_v(Float.valueOf(charging_vo.getCharger_v()));
									state.setCharger_i(Float.valueOf(charging_vo.getCharger_i()));
									state.setCharger_p(Float.valueOf(charging_vo.getCharger_p()));
									BigDecimal r = new BigDecimal(charging_vo.getRemaining_time());
									state.setRemaining_time(r.setScale(0, BigDecimal.ROUND_HALF_UP).toString());
									state.setSoc(charging_vo.getSoc());
									BigDecimal temperature = new BigDecimal(charging_vo.getHighestTemperature());
									state.setBattery_temperature(
											temperature.setScale(1, BigDecimal.ROUND_HALF_UP).toString());
								}
							}
						}
						stateList.add(state);
					}
					// sc.setStateList(list_direct);
					break;
				case 2:
					// 查询 6.12电池信息上送（可选）当前荷电状态 BIN码 1 系数为1% 0-100% 从redis中取得
					OmsChargerStateAlternate alternate_query = new OmsChargerStateAlternate();
					alternate_query.setCharger_id(chargerId);
					alternate_query.setPort_no(1);
					// 肯定是直流桩，所以查询 oms_charger_state_direct[直流充电桩状态表]
					List<OmsChargerStateAlternate> list_alternate = omsChargerStateAlternateDao
							.findExample(alternate_query, null, null, null, null);
					if (list_alternate == null || list_alternate.size() == 0) {
						return new JsonCommon(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
								OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
					}
					// 电压 功率 电流 SOC 从redis中取得
					// list.size() = 2 是预期查询结果
					// 已充电量 预计剩余时间 从6.10充电状态上送 中取得； 最高动力电池温度 BIN码 1 系数为1 偏移50
					// -50到200度 从 6.12电池信息上送（可选） 中取得
					// 电压 功率 电流 SOC 从从6.10充电状态上送 中取得；
					for (OmsChargerStateAlternate state : list_alternate) {
						if (state.getCharge_status() == 2) {
							String oms_msg_charge_jrnl = "";
							String battery_temperature = "";// 温度

							// 查询当前最新的充电流水号，通过charger_id端口号
							int port_no = state.getPort_no();

							String key_charging = chargerId + String.format("%02d", port_no) + "_status";
							Jedis redisClient = RedisClient.getConnect();

							String json = redisClient.get(key_charging);
							redisClient.close();
							if (json != null) {
								ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
								if (charging_vo != null) {
									state.setSoc(charging_vo.getSoc());
									state.setCharger_kwh(Float.valueOf(charging_vo.getCharger_kwh()));
									state.setCharger_v(Float.valueOf(charging_vo.getCharger_v()));
									state.setCharger_i(Float.valueOf(charging_vo.getCharger_i()));
									state.setCharger_p(Float.valueOf(charging_vo.getCharger_p()));
									BigDecimal r = new BigDecimal(charging_vo.getRemaining_time());
									state.setRemaining_time(r.setScale(0, BigDecimal.ROUND_HALF_UP).toString());
									state.setRemaining_time(charging_vo.getRemaining_time());
								}
							}
						}
						stateList.add(state);
					}
					break;
				default:
					return new JsonCommon(OmsConstant.ErrorCodeEnum.ChargerQueryNull.value(),
							OmsConstant.ErrorCodeEnum.ChargerQueryNull.desc());
				}
			}

		} // end for list

		sc.setStateList(stateList);

		// 以下是天气信息
		// 首先查询redis
		String key = "baidu_weather";
		String weather = "", city_temperature = "", pm25 = "", pm_level = "";
		Map<String, String> map_fromRedis = RedisClient.getMap(key);
		if (!map_fromRedis.isEmpty()) {
			weather = map_fromRedis.get("weather");
			city_temperature = map_fromRedis.get("city_temperature");
			pm25 = map_fromRedis.get("pm25");
			pm_level = map_fromRedis.get("pm_level");
		} else {
			String httpUrl = "http://apis.baidu.com/heweather/weather/free";
			String httpArg = "cityid=CN101260101";// cityid= city=guiyang
			String jsonResult = getWeather(httpUrl, httpArg);

			JSONObject json = (JSONObject) JSON.parse(jsonResult);
			JSONArray heWeather_data_array = json.getJSONArray("HeWeather data service 3.0");
			JSONObject daily_forecast_object = heWeather_data_array.getJSONObject(0);
			// {"wind":{"dir":"东风","deg":"142","sc":"4-5","spd":"21"},"hum":"75","fl":"18","pcpn":"0","tmp":"17",
			// "pres":"1011","cond":{"code":"101","txt":"多云"},"vis":"10"}
			JSONObject now_object = daily_forecast_object.getJSONObject("now");
			city_temperature = now_object.get("tmp").toString();
			JSONObject cond_object = now_object.getJSONObject("cond");
			weather = cond_object.get("txt").toString();
			// {"city":{"co":"1","so2":"8","o3":"76","no2":"31","aqi":"64","pm10":"75","pm25":"33","qlty":"良"}}
			JSONObject aqi_object = daily_forecast_object.getJSONObject("aqi");
			JSONObject city_object = aqi_object.getJSONObject("city");
			pm25 = city_object.get("pm25").toString();
			pm_level = city_object.get("qlty").toString();

			Map<String, String> map = new HashMap<String, String>();
			map.put("weather", weather);
			map.put("city_temperature", city_temperature);
			map.put("pm25", pm25);
			map.put("pm_level", pm_level);
			RedisClient.putMap(key, map);
			RedisClient.expire(key, 60 * 60);
		}
		sc.setWeather(weather);
		sc.setCity_temperature(city_temperature);
		sc.setPm25(pm25);
		sc.setPm_level(pm_level);

		return new JsonCommon(sc, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
				OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	/**
	 * @param httpUrl
	 *            :请求接口
	 * @param httpArg
	 *            :参数
	 * @return 返回结果
	 */
	public String getWeather(String httpUrl, String httpArg) {
		BufferedReader reader = null;
		String result = null;
		StringBuffer sbf = new StringBuffer();
		httpUrl = httpUrl + "?" + httpArg;

		try {
			URL url = new URL(httpUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			// 填入apikey到HTTP header
			connection.setRequestProperty("apikey", "ab6227fdf59629bafc400b551e420550");
			connection.connect();
			InputStream is = connection.getInputStream();
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String strRead = null;
			while ((strRead = reader.readLine()) != null) {
				sbf.append(strRead);
				sbf.append("\r\n");
			}
			reader.close();
			result = sbf.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public List<OmsChargerRate> findChargerRateByChargerId(String charger_id) {
		StringBuffer sql = new StringBuffer("select a.* from oms_charger_rate a,oms_charger b where b.charger_id='")
				.append(charger_id)
				.append("' and (a.rate_schema = b.rate_schema_bespeak_fee or a.rate_schema = b.rate_schema_charge_fee or a.rate_schema = b.rate_schema_service_fee)")
				.append(" and ( (a.start_time is null and a.end_time is null) or ( DATE_FORMAT(now(),'%H:%i') >= a.start_time AND a.end_time >= DATE_FORMAT(now(),'%H:%i')) )");

		return omsChargerRateDao.findDataBySqlOfClass(sql.toString(), OmsChargerRate.class, null);
	}

	@Override
	public JsonCommon getWeatherByCityId(String cityId) {
		// 以下是天气信息
		// 首先查询redis
		ScreenCharger sc = new ScreenCharger();
		String key = "baidu_weather_" + cityId;
		String weather = "", city_temperature = "", pm25 = "", pm_level = "";
		Map<String, String> map_fromRedis = RedisClient.getMap(key);
		if (!map_fromRedis.isEmpty()) {
			weather = map_fromRedis.get("weather");
			city_temperature = map_fromRedis.get("city_temperature");
			pm25 = map_fromRedis.get("pm25");
			pm_level = map_fromRedis.get("pm_level");
		} else {
			String httpUrl = "http://apis.baidu.com/heweather/weather/free";
			String httpArg = "cityid=" + cityId;// cityid= city=guiyang
			String jsonResult = getWeather(httpUrl, httpArg);

			JSONObject json = (JSONObject) JSON.parse(jsonResult);
			JSONArray heWeather_data_array = json.getJSONArray("HeWeather data service 3.0");
			JSONObject daily_forecast_object = heWeather_data_array.getJSONObject(0);
			// {"wind":{"dir":"东风","deg":"142","sc":"4-5","spd":"21"},"hum":"75","fl":"18","pcpn":"0","tmp":"17",
			// "pres":"1011","cond":{"code":"101","txt":"多云"},"vis":"10"}
			JSONObject now_object = daily_forecast_object.getJSONObject("now");
			city_temperature = now_object.get("tmp").toString();
			JSONObject cond_object = now_object.getJSONObject("cond");
			weather = cond_object.get("txt").toString();
			// {"city":{"co":"1","so2":"8","o3":"76","no2":"31","aqi":"64","pm10":"75","pm25":"33","qlty":"良"}}
			JSONObject aqi_object = daily_forecast_object.getJSONObject("aqi");
			JSONObject city_object = aqi_object.getJSONObject("city");
			pm25 = city_object.get("pm25").toString();
			pm_level = city_object.get("qlty").toString();

			Map<String, String> map = new HashMap<String, String>();
			map.put("weather", weather);
			map.put("city_temperature", city_temperature);
			map.put("pm25", pm25);
			map.put("pm_level", pm_level);
			RedisClient.putMap(key, map);
			RedisClient.expire(key, 60 * 60);
		}
		sc.setWeather(weather);
		sc.setCity_temperature(city_temperature);
		sc.setPm25(pm25);
		sc.setPm_level(pm_level);

		return new JsonCommon(sc, OmsConstant.SuccessCodeEnum.SuccessCode.value(),
				OmsConstant.SuccessCodeEnum.SuccessCode.desc());
	}

	@Override
	public JsonForList getChargerStatusByStationId(String stationId) {
		StringBuffer sql = new StringBuffer();
		sql.append(
				"select b.charger_id,b.serial_no,c.port_no,c.charge_status,'1' charger_type  from oms_station a,oms_charger b,oms.oms_charger_state_direct c ")
				.append("where a.station_id=b.station_id  and b.charger_id=c.charger_id and b.valid_flag=1 and a.station_id='"
						+ stationId + "' ")
				.append("union all ")
				.append("select b.charger_id,b.serial_no,c.port_no,c.charge_status,'2' charger_type  from oms_station a,oms_charger b,oms.oms_charger_state_alternate c ")
				.append("where a.station_id=b.station_id  and b.charger_id=c.charger_id and b.valid_flag=1 and a.station_id='"
						+ stationId + "' ");
		List<Map<String, Object>> listTmp = omsChargerDao.findDataBySql(sql.toString());

		for (Map<String, Object> mapTmp : listTmp) {
			String charger_id = (String) mapTmp.get("charger_id");
			int port_no = (int) mapTmp.get("port_no");
			int charger_type = Integer.parseInt((String) mapTmp.get("charger_type"));
			int charge_status = (int) mapTmp.get("charge_status");

			if (charger_id != null && charger_type > 0) {
				switch (charger_type) {// 1直流 2 交流
				case 1:
					// 查询 6.12电池信息上送（可选）当前荷电状态 BIN码 1 系数为1% 0-100% 从redis中取得
					// 电压 功率 电流 SOC 从redis中取得
					// 已充电量 预计剩余时间 从6.10充电状态上送 中取得； 最高动力电池温度 BIN码 1 系数为1 偏移50
					// -50到200度 从 6.12电池信息上送（可选） 中取得
					// 电压 功率 电流 SOC 从从6.10充电状态上送 中取得；
					if (charge_status == 2) {
						String oms_msg_charge_jrnl = "";
						String battery_temperature = "";// 温度

						String key_charging = charger_id + String.format("%02d", port_no) + "_status";
						Jedis redisClient = RedisClient.getConnect();

						String json = redisClient.get(key_charging);
						redisClient.close();

						if (json != null) {
							ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
							if (charging_vo != null) {
								// state.setSoc(charging_vo.getSoc());
								// state.setCharger_kwh(Float.valueOf(charging_vo.getCharger_kwh()));
								// state.setCharger_v(Float.valueOf(charging_vo.getCharger_v()));
								// state.setCharger_i(Float.valueOf(charging_vo.getCharger_i()));
								// state.setCharger_p(Float.valueOf(charging_vo.getCharger_p()));
								// BigDecimal r = new
								// BigDecimal(charging_vo.getRemaining_time());
								// state.setRemaining_time(r.setScale(0,
								// BigDecimal.ROUND_HALF_UP).toString());
								// state.setSoc(charging_vo.getSoc());
								// BigDecimal temperature = new
								// BigDecimal(charging_vo.getHighestTemperature());
								// state.setBattery_temperature(temperature.setScale(1,
								// BigDecimal.ROUND_HALF_UP).toString());
								mapTmp.put("soc", charging_vo.getSoc());
								mapTmp.put("charger_kwh", Float.valueOf(charging_vo.getCharger_kwh()));
								mapTmp.put("charger_v", Float.valueOf(charging_vo.getCharger_v()));
								mapTmp.put("charger_i", Float.valueOf(charging_vo.getCharger_i()));
								mapTmp.put("charger_p", Float.valueOf(charging_vo.getCharger_p()));
								BigDecimal r = new BigDecimal(charging_vo.getRemaining_time());
								mapTmp.put("remaining_time", r.setScale(0, BigDecimal.ROUND_HALF_UP).toString());
								BigDecimal temperature = new BigDecimal(charging_vo.getHighestTemperature());
								mapTmp.put("battery_temperature",
										temperature.setScale(1, BigDecimal.ROUND_HALF_UP).toString());

							}
						}
					}

					break;
				case 2:
					// 查询 6.12电池信息上送（可选）当前荷电状态 BIN码 1 系数为1% 0-100% 从redis中取得
					// 电压 功率 电流 SOC 从redis中取得
					// 已充电量 预计剩余时间 从6.10充电状态上送 中取得； 最高动力电池温度 BIN码 1 系数为1 偏移50
					// -50到200度 从 6.12电池信息上送（可选） 中取得
					// 电压 功率 电流 SOC 从从6.10充电状态上送 中取得；

					if (charge_status == 2) {
						String oms_msg_charge_jrnl = "";
						String battery_temperature = "";// 温度
						String key_charging = charger_id + String.format("%02d", port_no) + "_status";
						Jedis redisClient = RedisClient.getConnect();

						String json = redisClient.get(key_charging);
						redisClient.close();

						if (json != null) {
							ChargeDataUploadingVO charging_vo = JSON.parseObject(json, ChargeDataUploadingVO.class);
							if (charging_vo != null) {
								// state.setSoc(charging_vo.getSoc());
								// state.setCharger_kwh(Float.valueOf(charging_vo.getCharger_kwh()));
								// state.setCharger_v(Float.valueOf(charging_vo.getCharger_v()));
								// state.setCharger_i(Float.valueOf(charging_vo.getCharger_i()));
								// state.setCharger_p(Float.valueOf(charging_vo.getCharger_p()));
								// BigDecimal r = new
								// BigDecimal(charging_vo.getRemaining_time());
								// state.setRemaining_time(r.setScale(0,
								// BigDecimal.ROUND_HALF_UP).toString());
								// state.setRemaining_time(charging_vo.getRemaining_time());
								mapTmp.put("soc", charging_vo.getSoc());
								mapTmp.put("charger_kwh", Float.valueOf(charging_vo.getCharger_kwh()));
								mapTmp.put("charger_v", Float.valueOf(charging_vo.getCharger_v()));
								mapTmp.put("charger_i", Float.valueOf(charging_vo.getCharger_i()));
								mapTmp.put("charger_p", Float.valueOf(charging_vo.getCharger_p()));
								BigDecimal r = new BigDecimal(charging_vo.getRemaining_time());
								mapTmp.put("remaining_time", r.setScale(0, BigDecimal.ROUND_HALF_UP).toString());

							}
						}
					}

					break;
				default:
					break;
				}
			}
		}

		JsonForList json = new JsonForList();
		json.setCode(OmsConstant.SuccessCodeEnum.SuccessCode.value());
		json.setList(listTmp);
		json.setMsg(OmsConstant.SuccessCodeEnum.SuccessCode.desc());
		return json;
	}

}